package org.xiaov.core.bean;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xiaov.execption.XiaovUtilsException;

import java.util.List;

/**
 * <p>
 * JSON帮助类
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/4/4 22:57
 */
public class JSONHelper {
    private static final Logger log = LoggerFactory.getLogger(JSONHelper.class);

    /**
     * 将object转化为json字符串
     *
     * @param obj
     * @return
     */
    public static String toJSONString(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("【Object】>>【String】类型转化失败", e);
            throw new XiaovUtilsException("【Object】>>【String】类型转化失败");
        }
    }

    /**
     * 将json字符串转化成指定的Java对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, clazz);
        } catch (Exception e) {
            log.error("【JSON】>>【"+clazz.getName()+"】类型转化失败", e);
            throw new XiaovUtilsException("【JSON】>>【Object】类型转化失败");
        }
    }

    /**
     * 将json字符串转化成List
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> parseArray(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, new TypeReference<List<T>>() {
            });
        } catch (Exception e) {
            log.error("【JSON】>>【List】类型转化失败", e);
            throw new XiaovUtilsException("【JSON】>>【List】类型转化失败");
        }
    }
}
